<?php

namespace common\base;

use Yii;
use yii\db\Exception;

/**
 * Model is the base class for data models.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class Model extends \yii\base\Model {

    use \common\traits\ModelErrors;
    use \common\traits\DataPierces;

    const TRANS_FUNC_PREFIX = 'transact';

    /**
     * AR事务封装
     *
     * @param $method
     * @param null $error
     * @return mixed|void
     * @throws ModelHttpException
     */
    public function executeTransaction($method, $error = null) {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $executeResult = call_user_func(array($this, self::TRANS_FUNC_PREFIX . ucfirst($method)));
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            if ($error !== null) {
                return $error;
            }
            $msg = $e->getMessage();
            if (YII_DEBUG) {
                $msg .= $e->errorInfo;
            }
            return $this->saveError($msg, false);
        }
        return $executeResult;
    }

    /**
     * Populates the model with input data.
     *
     * @param array $data
     * @param string $formName set default value ''
     * @return bool whether `load()` found the expected form in `$data`.
     */
    public function load($data, $formName = '') {
        return parent::load($data, $formName);
    }

}
